﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CommonFunction
{
    /// <summary>
    /// 滤波程序
    /// </summary>
    public class WaveFilteringHelper : WaveFilteringInterface
    {
        public unsafe double[] WaveFiltering(double[] rawData, int step = 3)
        {
            double[] smooth = new double[rawData.Length];
            fixed (double* o = smooth, r = rawData)
            {
                for (int i = step; i < rawData.Length; i++)
                {
                    double total = 0;
                    int s = step * 2 + 1;
                    for (int j = i - step; j < i + step + 1; j++)
                    {
                        if (j < rawData.Length)
                        {
                            total += r[j];
                        }
                        else
                        {
                            break;
                        }
                    }
                    o[i] = total / s;
                }

                //Head fill
                for (int i = 0; i < step; i++)
                {
                    o[i] = o[step];
                }
                //Tail fill
                int tail = rawData.Length - (rawData.Length % (step + 1)) - 1;
                for (int j = tail; j < rawData.Length; j++)
                {
                    o[j] = o[tail - 1];
                }

            }
            return smooth;
        }
    }

    interface WaveFilteringInterface
    {
        /// <summary>
        /// 移动平均,曲线平滑
        /// </summary>
        /// <param name="rawData">原曲线数组</param>
        /// <param name="step">步长</param>
        /// <returns></returns>
        double[] WaveFiltering(double[] rawData, int step = 3);
    }
}
